package com.lmx.persistence.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Service;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.util.CommonUtil;
import com.lmx.common.util.QCloudUtil;
import com.lmx.persistence.service.common.BaseCrudServiceImpl;
import com.lmx.repoDomain.tmodel.VideoInfo;

/**
 * 视频信息service实现
 *
 * @author ytche
 * @date 2017年8月18日
 *
 */
@Service
public class VideoInfoServiceImpl extends BaseCrudServiceImpl<VideoInfo>
		implements VideoInfoService {
	private static Log logger = LogFactory.getLog(VideoInfoServiceImpl.class);

	@Override
	public VideoInfo create(VideoInfo entity) {
		// 默认视频十四天后过期
		if (entity.getExpireTime() == null) {
			Long expireTime = System.currentTimeMillis() / 1000 + 3600 * 24
					* 14;
			entity.setExpireTime(expireTime.intValue());
		}
		return super.create(entity);
	}

	@Override
	public VideoInfo update(VideoInfo entity) {
		if (entity.getDelStatus().equals(CommonConstants.DEL_STATUS_YES_1)
				&& CommonConstants.DEFAULT_STATUS_YES_1.equals(entity
						.getFileExistStatus())) {
			if (QCloudUtil.deleteVideo(entity.getFileId())) {
				entity.setFileExistStatus(CommonConstants.DEFAULT_STATUS_NO_0);
			}
		}
		return super.update(entity);
	}

	@Override
	public void delete(final VideoInfo entity) {
		if (CommonConstants.DEFAULT_STATUS_YES_1.equals(entity
				.getFileExistStatus())) {
			QCloudUtil.deleteVideo(entity.getFileId());
		}
		super.delete(entity);
	}

	@Override
	public void deleteById(final long entityId) {
		VideoInfo videoInfo = super.findOne(entityId);
		this.delete(videoInfo);
	}

	@Override
	public void DeleteExpireVideo() {
		List<VideoInfo> videos = this.getExpireVideo(null);
		for (VideoInfo videoInfo : videos) {
			if (QCloudUtil.deleteVideo(videoInfo.getFileId())) {
				videoInfo
						.setFileExistStatus(CommonConstants.DEFAULT_STATUS_NO_0);
				super.save(videoInfo);
			}
		}
	}

	private List<VideoInfo> getExpireVideo(Integer expireTime) {
		expireTime = expireTime == null ? CommonUtil.getDayBegin() : expireTime;
		String queryStr = "from VideoInfo where delStatus = 0 and fileExistStatus=1 and expireTime < :expireTime";
		return super.em.createQuery(queryStr)
				.setParameter("expireTime", expireTime).getResultList();
	}
}
